package com.cxps.server.handler;

import com.cxps.cloud.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * JWT登录授权过滤器
 *
 * @author YouCai.Liu
 * @since 2021/10/24
 * ...
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    // 请求头里存储token的key
    private static final String TOKEN_HEADER = "AuthToken";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {

        // 从请求头获取Token
        String authToken = request.getHeader(TOKEN_HEADER);
        if (null != authToken) {
            // 验证token是否有效
            if (!JwtTokenUtil.isTokenExpired(authToken)) {

                // 从token获取用户主题信息
                String clientUsername = JwtTokenUtil.getUserNameFromToken(authToken);
                log.info("checking username：{}", clientUsername);

                /**
                 * SpringSecurity的上下文用于存储用户的信息, 但是会在一个过滤器链执行完毕后就销毁,
                 * 默认的是使用Session, SpringSecurity会从Session中拿到用户信息并放在上下文中,
                 * 我们这里用token，将session禁用了，就没地方去取用户信息了，所以我们每次都需要重新校验用户，
                 * 交给SpringSecurity的上下文
                 */
                if (clientUsername != null && SecurityContextHolder.getContext().getAuthentication() == null) {

                    // TODO: 2021/11/6 设计缺陷 start：直接从JWT取数据非常不安全，最好和服务端有一次交互
                    // 获取 jwt 里所有负载信息
                    Claims claims = JwtTokenUtil.getClaimsFromToken(authToken);

                    // 获取权限列表
                    List<String> auths = (List<String>) claims.get("auth");
                    List<GrantedAuthority> authorities = new ArrayList<>();
                    for (String auth : auths) {
                        authorities.add(new SimpleGrantedAuthority(auth));
                    }

                    // 构建 security 需要的那个用户对象信息
                    UserDetails userDetails = User.builder()
                            .username(clientUsername)
                            .password("")
                            .authorities(authorities)
                            .build();
                    // TODO: 2021/11/6 设计缺陷 end：直接从JWT取数据非常不安全，最好和服务端有一次交互

                    // 重新将用户信息放入springSecurity
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }

}
